package cn.linjianhui.article.utils;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

public class MapUtil {
    public static <T> T mapToObj(Object source, Class<T> tClass) {
        T target = null;
        try {
            if(source != null) {
                target = tClass.newInstance();
                BeanUtils.copyProperties(source, target);
            }
        }catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return target;
    }

    public static <T> List<T> mapToAnotherList(List<?> list, Class<T> tClass) {
        List<T> result = new ArrayList<>();

        if(list == null || list.size() ==0)
            return result;

        try {
            for (Object item : list) {
                if(item != null) {
                    T target = tClass.newInstance();
                    BeanUtils.copyProperties(item, target);
                    result.add(target);
                }
            }
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }

        return result;
    }
}
